# THIS SHIT IS JUST WEB FRAMEWORK STUFF IT COULD BE ANYTHING
import cherrypy
from google.appengine.api import channel
import wsgiref.handlers
from jinja2 import Environment, FileSystemLoader, TemplateNotFound
import os
from google.appengine.api import memcache

template_dirs = []
template_dirs.append(os.path.join(os.path.dirname(__file__), 'templates'))
# THIS SHIT IS JUST WEB FRAMEWORK STUFF IT COULD BE ANYTHING

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util

#gets a jinja template from the "templates" folder
def get_template(name):
    env = Environment(loader = FileSystemLoader(template_dirs))
    try:
        return env.get_template(name)
    except TemplateNotFound:
        raise TemplateNotFound(name)

class LuaAppEngine(object):
    
    @cherrypy.expose
    def index(self):
        return get_template('index.html').render()
    
    @cherrypy.expose
    def tetrinet(self,key="Test",name=None):
        key = key.lower()
        if name == None:
            import random
            name = "Guest"+str(random.randint(0,999));
        players = memcache.get(key)
        if players == None:
            players = [None,None,None,None,None,None]
        
        
        if key+name in players:
            return "Player with name already exists. Please choose another."
            
        token = channel.create_channel(key+name)
        for i in range(0,6):
            if players[i] == None:
                players[i] = key+name
                memcache.set(key,players)
                
                s = [];
                for p in players:
                    if p:
                        s.append(str(p[len(key):]))
                    else:
                        s.append("None")
                return get_template('tetrinet.html').render(token=token, key=key, player=i,name=name,known_players=",".join(s))
        return "This game is full"
        
        
    @cherrypy.expose
    def chat(self,key="Test"):
        key = key.lower()
        players = memcache.get(key)
        if players != None:
            for p in players:
                if p != None:
                    channel.send_message(p, str(cherrypy.request.body.getvalue()))
        else:
            pass

#---------------------------------------------------------------------------
# Start the server under Google AppEngine
#---------------------------------------------------------------------------
app = cherrypy.tree.mount(LuaAppEngine(), "/")
wsgiref.handlers.CGIHandler().run(app)